package nacos

import (
	"github.com/apache/dubbo-go/common"
	"github.com/beego/beego/v2/core/logs"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/model"
	"github.com/nacos-group/nacos-sdk-go/util"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

var (
	gRunMode string
)

func clientInit() {

	logs.Debug("开始测试nacos服务注册....")
	sc := []constant.ServerConfig{
		{
			IpAddr: "192.168.11.120",
			Port:   8848,
		},
	}

	cc := constant.ClientConfig{

		NamespaceId:         "e525eafa-f7d7-4029-83d9-008937f9d468", //namespace id
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "logs/nacos",
		CacheDir:            "logs/nacos/cache",
		RotateTime:          "1h",
		MaxAge:              3,
		LogLevel:            "debug",
	}

	// a more graceful way to create naming client
	client, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)

	if err != nil {
		panic(err)
	}

	localAddr := common.GetLocalIp()
	//Register with default cluster and group
	//ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
	ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
		Ip:          localAddr,
		Port:        8080,
		ServiceName: "ipcc",
		Weight:      10,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
		Metadata:    map[string]string{"idc": "shenzhen"},
	})

	ExampleServiceClient_Subscribe(client, &vo.SubscribeParam{
		ServiceName: "ipcc",
		SubscribeCallback: func(services []model.SubscribeService, err error) {
			logs.Debug("\n\n callback return services:%s \n\n", util.ToJsonString(services))
		},
	})
}

func NacosInit(runMode, namespaceId, addr string, port uint64) error {
	//clientInit()
	gRunMode = runMode

	return configInit(namespaceId, addr, port)
}
